import { getStorePage, getUserPage } from "@/api/common";
import {
  addCrossStoreOrder,
  cancelCrossStoreOrder,
  confirmCrossStoreOrder,
  getCrossStoreOrderList,
  getCrossStoreOrderSum
} from "@/api/order/crossStore";
import { DictTag } from "@/components/common/DictTag";
import { addDialog } from "@/components/ReDialog";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { useRouterNavigation } from "@/router/utils";
import { useUserStoreHook } from "@/store/modules/user";
import { dealDataExcept, dealDataRide } from "@/utils/common";
import { message } from "@/utils/message";
import { goodsCodeRend, goodsNameRend } from "@/utils/tableColumns";
import type { PaginationProps } from "@pureadmin/table";
import { cloneDeep } from "@pureadmin/utils";
import dayjs from "dayjs";
import { ElTag } from "element-plus";
import { h, onMounted, reactive, ref, watch } from "vue";
import editForm from "../form/index.vue";
import type { FormItemProps } from "../utils/types";

export function useShipper() {
  const form = reactive({
    storeIds: useUserStoreHook().loginStoreId,
    bizType: 2,
    crossStoreOrderCode: "",
    goodsName: "",
    goodsCode: "",
    barCode: "",
    specName: "",
    specCode: "",
    salesStoreId: "",
    buyStoreId: "",
    suborderOrderStatus: 999,
    createUserId: "",
    businessDate: [],
    businessDateStart: "",
    businessDateEnd: "",
    pageNum: 1,
    pageSize: 20
  });

  const loading = ref(false);
  const dataList = ref([]);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    background: true,
    pageSizes: [20, 50, 100, 200]
  });

  const tabType = ref(999);
  const tabList = ref([
    { label: "全部", name: 999, count: 0 },
    { label: "待审核", name: 0, count: 0 },
    { label: "待确认", name: 2, count: 0 },
    { label: "已完成", name: 3, count: 0 },
    { label: "已驳回", name: 1, count: 0 },
    { label: "已取消", name: 4, count: 0 }
  ]);

  const columns: TableColumnList = [
    {
      fixed: "left",
      type: "expand",
      slot: "expand"
    },
    {
      label: "业务日期",
      prop: "storeCode",
      formatter: ({ businessDate }) => dayjs(businessDate).format("YYYY-MM-DD"),
      width: 150
    },
    {
      label: "跨店销售订单号",
      prop: "crossStoreOrderCode",
      minWidth: 210
    },
    {
      label: "销售门店",
      prop: "storeName",
      minWidth: 200
    },
    {
      label: "出货仓库",
      prop: "deliveryDepositoryName",
      minWidth: 150
    },
    {
      label: "购买门店",
      prop: "buyStoreName",
      minWidth: 155
    },
    {
      label: "收货仓库",
      prop: "receiveDepositoryName",
      minWidth: 150
    },
    {
      label: "状态",
      prop: "suborderOrderStatus",
      minWidth: 90,
      cellRenderer: ({ row }) => getOrderStatus(row.suborderOrderStatus)
    },
    {
      label: "订单总金额",
      prop: "orderPrice",
      minWidth: 120,
      formatter: ({ totalPrice }) => dealDataExcept(totalPrice) || "--"
    },
    {
      label: "商品总数量",
      prop: "totalCommodities",
      minWidth: 120
    },
    {
      label: "创建人",
      prop: "createUser",
      width: 150
    },
    {
      label: "创建时间",
      prop: "gmtCreate",
      formatter: ({ gmtCreate }) => dayjs(gmtCreate).format("YYYY-MM-DD HH:mm"),
      minWidth: 180
    },
    {
      label: "备注",
      prop: "des",
      minWidth: 180,
      showOverflowTooltip: true,
      formatter: ({ des }) => des || "--"
    },
    {
      label: "操作",
      fixed: "right",
      align: "center",
      width: 80,
      slot: "operation"
    }
  ];

  const childColumns: TableColumnList = [
    {
      label: "商品名称/规格名称",
      prop: "specName",
      minWidth: 220,
      align: "left",
      // slot: "specName",
      cellRenderer: goodsNameRend
    },
    {
      label: "商品编码/规格编码",
      prop: "specCode",
      align: "left",
      minWidth: 150,
      // slot: "specCode",
      cellRenderer: goodsCodeRend
    },
    {
      label: "商品条码",
      prop: "barCode",
      minWidth: 120
    },
    {
      label: "状态",
      prop: "orderItemStatus",
      minWidth: 100,
      cellRenderer: ({ row }) => getRemindStatus(row.reminderState)
    },
    {
      label: "商品类型",
      prop: "goodsType",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <DictTag dict-type="PRODUCT_TYPE" dict-value={row.goodsType} />
      )
    },
    {
      label: "库存单价",
      prop: "buyPrice",
      minWidth: 120,
      formatter: ({ salePrice }) => dealDataExcept(salePrice) || "--"
    },
    {
      label: "商品数量",
      prop: "goodsAmount",
      minWidth: 120
    },
    {
      label: "金额",
      prop: "totalPrice",
      minWidth: 120,
      formatter: ({ totalPrice }) => dealDataExcept(totalPrice) || "--"
    }
  ];

  // 获取订单状态
  const getOrderStatus = status => {
    if (status == null) {
      return "--";
    }
    // 订单状态 0 待审核 1 已驳回 2 待确认 3 已完成 4 已取消
    let statusMap = {
      0: { text: "待审核", type: "warning" },
      2: { text: "待确认", type: "warning" },
      3: { text: "已完成", type: "success" },
      1: { text: "已驳回", type: "danger" },
      4: { text: "已取消", type: "danger" }
    };
    let obj = statusMap[status];
    if (!obj) {
      return "--";
    }
    return h(
      ElTag,
      {
        type: obj.type
      },
      () => obj.text
    );
  };

  // 获取订单商品状态
  const getRemindStatus = status => {
    if (status == null) {
      return "--";
    }
    // 提醒状态 0 待审核 1 发货中 2 已发货 3 已完成 4 已驳回 5 已关闭
    let statusMap = {
      0: { text: "待审核", type: "warning" },
      1: { text: "发货中", type: "primary" },
      2: { text: "已发货", type: "primary" },
      3: { text: "已完成", type: "success" },
      4: { text: "已驳回", type: "danger" },
      5: { text: "已关闭", type: "danger" },
      6: { text: "待确认", type: "warning" }
    };
    let obj = statusMap[status];
    if (!obj) {
      return "--";
    }
    return h(
      ElTag,
      {
        type: obj.type
      },
      () => obj.text
    );
  };

  function resetForm(formEl) {
    if (!formEl) return;
    tabType.value = 999;
    formEl.resetFields();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;

    // 处理请求参数
    let tempForm = { ...form };
    if (tempForm.businessDate && tempForm.businessDate.length > 0) {
      tempForm.businessDateStart = tempForm.businessDate[0];
      tempForm.businessDateEnd = tempForm.businessDate[1];
    } else {
      tempForm.businessDateStart = "";
      tempForm.businessDateEnd = "";
    }
    delete tempForm.businessDate;

    // 处理状态
    tempForm.suborderOrderStatus = tabType.value;
    if (tempForm.suborderOrderStatus == 999)
      delete tempForm.suborderOrderStatus;

    // 销售门店
    if (tempForm.salesStoreId) {
      tempForm.storeIds += "," + tempForm.salesStoreId;
    }

    tempForm.pageNum = pagination.currentPage;
    tempForm.pageSize = pagination.pageSize;

    const { data } = await getCrossStoreOrderList(tempForm);
    dataList.value = data.records;
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.pageNum;

    // 统计
    delete tempForm.suborderOrderStatus;
    const sumReq = await getCrossStoreOrderSum(tempForm);
    let countList = sumReq.data || [];
    let total = 0;
    let tempTabList = cloneDeep(tabList.value);
    tempTabList.forEach(v => (v.count = 0));
    countList.forEach(v => {
      let findTab = tempTabList.find(j => j.name === v.status);
      if (findTab) {
        findTab.count = v.storeOrderNum || 0;
      }
      total += Number(v.storeOrderNum);
    });
    tempTabList[0].count = total;
    tabList.value = tempTabList;

    setTimeout(() => {
      loading.value = false;
    }, 200);
  }

  watch(tabType, () => {
    onSearch();
  });

  const formRef = ref();

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}跨店销售单`,
      sureBtnLoading: true,
      props: {
        formInline: {
          id: row?.id ?? "",
          buyStoreId: row?.buyStoreId ?? undefined,
          receiveDepositoryId: row?.receiveDepositoryId ?? undefined,
          deliveryDepositoryId: row?.deliveryDepositoryId ?? undefined,
          addItemList: row?.addItemList ?? undefined,
          updateItemList: row?.updateItemList ?? undefined,
          deleteOrderItemIds: row?.deleteOrderItemIds ?? [],
          fareType: row?.fareType ?? 1, // 运费类型 1包邮 2提前支付 3到付
          fare: row?.fare ?? undefined,
          orderNum: row?.orderNum ?? undefined,
          orderPrice: row?.orderPrice ?? undefined,
          des: row?.des ?? "",
          dataList: []
        },
        storeList: storeList.value
      },
      class: "hzbh",
      width: "99%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options, closeLoading }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline;
        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          done();
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            console.log("curData", curData);

            // 商品判断
            let goodsList = curData.dataList;
            if (goodsList.length == 0) {
              closeLoading();
              return message("请选择商品", { type: "warning" });
            }

            for (let index = 0; index < goodsList.length; index++) {
              const item = goodsList[index];
              if (!item.spdj || !item.spsl) {
                closeLoading();
                return message(
                  `商品: '${item.goodsName}' 商品单价、商品数量不可为空`,
                  {
                    type: "warning"
                  }
                );
              }
            }

            let loginStoreId = useUserStoreHook().loginStoreId;
            let loginSotre = useUserStoreHook().storeList.find(
              v => v.id == loginStoreId
            );
            console.log("hh", loginSotre);

            const params = {
              storeId: loginStoreId,
              // storeName: loginSotre.storeName, // 门店名称
              buyStoreId: curData.buyStoreId, // 购买门店id
              // buyStoreName:
              //   storeList.value.find(v => v.id == curData.buyStoreId)
              //     ?.storeName || "", // 购买门店
              deliveryDepositoryId: curData.deliveryDepositoryId, // 	销售门店仓库id
              receiveDepositoryId: curData.receiveDepositoryId, // 	收货(购买)仓库id
              // deliveryDepositoryName: curData.depositoryName || "", // 仓库名称
              totalCommodities: 0, // 	商品数量
              totalPrice: dealDataRide(curData.orderPrice), // 商品总价
              des: curData.des, // 备注
              orderItemRequests: [] // 新增商品列表
            };

            // 新增时，需要传递的参数 addItemList 不需要传 updateItemList
            let totalNum = 0;
            params.orderItemRequests = goodsList.map(v => {
              let obj = {
                goodsAmount: v.spsl, // 商品数量
                goodsCode: v.goodsCode,
                goodsId: v.goodsId,
                goodsType: v.goodsType,
                specCode: v.specCode,
                salePrice: dealDataRide(v.spdj) // 商品单价
              };
              totalNum += Number(v.spsl);
              return obj;
            });
            params.totalCommodities = totalNum;
            // 实际开发先调用新增接口，再进行下面操作
            console.log("params--------新增", params);
            const { code } = await addCrossStoreOrder(params);
            if (code == 200) {
              chores();
            } else {
              closeLoading();
            }
          } else {
            closeLoading();
          }
        });
      }
    });
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  const { push } = useRouterNavigation();
  function openDetil(row?: FormItemProps) {
    push({
      path: `/orderManag/shipperPrepar/detail`,
      query: { id: row.id }
    });
  }

  const storeList = ref([]);
  let supplierList = ref([]);
  const userList = ref([]);
  /**
   * 获取公共数据，包括供应商列表和仓库列表
   * @param params - 查询参数
   */
  async function getCommon() {
    // 门店列表
    const params = {
      status: 0,
      pageNum: 1,
      pageSize: 999
    };

    getStorePage(params).then(res => {
      storeList.value = res.data?.records || [];
    });

    // 获取用户列表
    let userParams = {
      bizType: 2,
      enableStatus: 1,
      pageNum: 1,
      pageSize: 500
    };
    getUserPage(userParams).then(res => {
      userList.value = res.data?.records || [];
    });
  }

  async function handleOpt(row, type) {
    console.log(row);
    let params = {
      crossStoreOrderCode: row.crossStoreOrderCode
    };
    const res =
      type == 2
        ? await confirmCrossStoreOrder(params)
        : await cancelCrossStoreOrder(params);
    if (res.code != 200) return;
    message(type == 2 ? "确认成功" : "取消成功", { type: "success" });
    onSearch();
  }

  onMounted(() => {
    onSearch();

    // 供应商列表
    getCommon();
  });

  return {
    form,
    loading,
    columns,
    childColumns,
    dataList,
    pagination,
    tabType,
    tabList,
    supplierList,
    userList,
    storeList,
    useRenderIcon,
    /** 搜索 */
    onSearch,
    /** 重置 */
    resetForm,
    handleSizeChange,
    handleCurrentChange,
    openDialog,
    openDetil,
    handleOpt
  };
}
